package cn.edu.zjut.security;

import cn.edu.zjut.base.BaseController;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author:ZhouDan
 * @date: 2020/8/10
 * @version: 1.0
 */
@Slf4j
@Component
@RestController
public class MyAuthenticationSuccessHandler extends BaseController implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HttpSession session = request.getSession();
        // 让以前的session失效
        session.invalidate();
        // 创建新的session
        session = request.getSession();
        session.setAttribute("SESSION_USER", userDetails);
        session.setAttribute("SESSION_USERID", userDetails.getUsername());
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("token", UUID.randomUUID().toString().replace("-", ""));
        Map<String, Object> map = response(200, userMap);
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> map1 : map.entrySet()) {
            json.put(map1.getKey(), map1.getValue());
        }
        out.write(json.toString());
    }
}
